# Import required modules.
import gtk
import gtk.glade
import Graphics.Canvas
import Graphics.Base
import Graphics.Item
import Graphics.DetailedItem
import Core.GeneName
import cairo
import goocanvas
import Core.Seqimport
import datetime
import matplotlib.pyplot as pp

class Loader():
    def __init__(self):
        self.wTree  = gtk.glade.XML("loader.glade")
        self.window = self.wTree.get_widget("mainwindow")
        self.window.connect("delete-event", self.end)
        self.window.set_modal(True)

    def show(self):
        self.window.show_all()

    def end(self, w):
        self.window.destroy()


class Main():
    def __init__(self):
        self.wTree = gtk.glade.XML("GUI/GUI.glade")
        self.window = self.wTree.get_widget("mainwindow")
        self.window.connect("destroy", self.end)

        self.window.resize(800,600)
        self.scrwin = self.wTree.get_widget("summaryscene")
        self.scrwin.connect("button_press_event", self.on_press)
        self.scrwin.connect("motion_notify_event", self.on_hover)

        self.dtlwin = self.wTree.get_widget("detailscene")
        self.searchbutton = self.wTree.get_widget("searchbutt")
        self.entrybox = self.wTree.get_widget("searchentry")
        self.entrybox.connect("activate", self.search_clicked)
        self.searchbutton.connect("clicked",self.search_clicked)
        self.canvas = None
        self.detailcanvas = None
        self.upstream = None
        self.repnoint = 1
        self.window.show_all()
        self.current_selected = None
        self.current_hover = None

        self.menu = gtk.Menu()
        self.menu_name = gtk.MenuItem("")
        self.menu.append(self.menu_name)

    def clear_detail(self):
        if self.detailcanvas is not None:
            self.dtlwin.remove(self.detailcanvas)
            self.detailcanvas = None

    def on_press(self,i,w):


        self.clear_detail()
        self.detailcanvas = Graphics.Canvas.Canvas()
        self.dtlwin.add(self.detailcanvas)
        item = None
        try:
            item = self.canvas.get_items_at(w.x, w.y, self.canvas.create_cairo_context())[0].get_parent().get_parent()

            if isinstance(item, Graphics.Item.Item):
                self.current_selected = item
        except:
                self.current_selected = None

        self.selected_gene = self.canvas.current_selected
        rendered_item= Graphics.DetailedItem.Item(self.selected_gene, self.detailcanvas, self. selected_gene.list_of_positions,1 ,1)
        if item is not None:

            desc = item.gene.name + " (" + item.gene.chr + ":" + item.gene.start + "-" + item.gene.end + ")"
            goocanvas.Text(parent=self.detailcanvas.get_root_item(), x=15, y=5, text=desc, fill_color="black", font="consolas")
            self.detailcanvas.set_my_bounds(rendered_item.size[0],  50)
            self.detailcanvas.show()
        else:
            self.clear_detail()
        if w.button == 3:
            #self.menu_name.set_label(self.selected_gene.name)
            #self.menu.popup(None, None, None, w.button, w.time, None)
            #self.menu.show_all()
            pass



    def on_hover(self, i, w):
        """
        Dynamically show the item name on the window title bar
        """
        try:
            item = self.canvas.get_items_at(w.x, w.y, self.canvas.create_cairo_context())[0].get_parent().get_parent()

            if isinstance(item, Graphics.Item.Item):
                self.current_hover = item
                self.window.set_title(self.current_hover.name)

        except:
                self.current_selected = None

        pass


    def repchanged(self, w):
        pass
        #self.repnoint = int(w.get_active_text())

    def do_events(self):
        while gtk.events_pending():
                gtk.main_iteration()

    def new_canvas(self):
        if self.canvas is not None:
            self.scrwin.remove(self.canvas)
            self.canvas = None
            del self.canvas
            self.upstream = None
            del self.upstream
        self.canvas = Graphics.Canvas.Canvas()
        self.scrwin.add(self.canvas)
        data_file = "Data/seq-2kb"
        x = Core.Seqimport.Parse(data_file, "r")
        found_sites = x.motif_finder(self.entrybox.get_text(), x.run())
        self.width = 0
        self.height = 0
        #GENE_NUMBER = len(self.upstream.motif_list_feature)
        height = 0
        feature_no = 0
        text = "Motif searched: " + self.entrybox.get_text() + " Data file: " +  data_file + " Date:" + datetime.datetime.now().strftime("%c") + " RENDERED BY UPSTREAM "
        self.text = goocanvas.Text(parent=self.canvas.get_root_item() ,x=15,y=5, text = text, fill_color = "black", font="consolas")
        list_of_motif_pos =[]
        gene_no = 0
        cons_file = open("Export/rangeforcons_%s.txt" % self.entrybox.get_text(), "w")
        gene_file = open("Export/genefile_%s.txt" % self.entrybox.get_text(), "w")
        for feature in found_sites:
            #gene = self.upstream.motif_list_feature[j]
            print "%s processed successfully in range %s" % (feature[0].name, feature[0].chr)
            gene_file.write("%s \n" % feature[0].name)
            gene_no +=1
            list_of_pos=[]
            for k in feature[1]:
                list_of_pos.append([k.start(), k.end()])
                print k.start(), k.end
                list_of_motif_pos.append(k.start() - 1000)
                cons_file.write("%s %d %d %s \n" % (feature[0].chr, k.start() + int(feature[0].start) - 50, k.end() + int(feature[0].start) + 50, feature[0].name))
            x = Graphics.Item.Item(feature[0], self.canvas, list_of_pos, feature_no, height)
            feature_no += 1
            height += x.size[1]
            self.canvas.set_my_bounds(x.size[0], height + 50)
            self.width = x.size[0]
            self.height = height + 50


        gene_file.close()
        cons_file.close()
        print "%s genes will be graphed. please wait." % gene_no
        from  matplotlib import pyplot as pp
        #from scipy import stats
        #print stats.normaltest(list_of_motif_pos, axis=None)
        pos = open("Export/%s_positions.txt", "w")
        for l in list_of_motif_pos:
            pos.write("%d\n" % l)
        pos.close()

        pp.hist(list_of_motif_pos, 39)
        pp.xlabel("Relative location to TSS(bp)")
        pp.ylabel("Number of genes")

        pp.savefig("Export/%s_hist.pdf" % self.entrybox.get_text(), format="pdf")
        pp.clf()
        self.canvas.show()
        self.canvas.connect("button_press_event", self.on_press)
        self.window.show_all()
        DRAW_WIDTH = self.width
        DRAW_HEIGHT = self.height
        s = cairo.ImageSurface(cairo.FORMAT_ARGB32, DRAW_WIDTH, DRAW_HEIGHT)
        c1 = cairo.Context(s)
        c1.rectangle(0,0,DRAW_WIDTH,DRAW_HEIGHT)
        c1.set_source_rgb(1, 1, 1)
        c1.fill()

        self.canvas.render(c1)


        s.write_to_png("Export/" + self.entrybox.get_text() + ".png")

    def search_clicked(self, w):
        """
        When search button is clicked, this event is triggered.
        """

        if self.entrybox.get_text() <> "":

            self.new_canvas()

    def end(self,w):
        gtk.main_quit()

x = Main()
gtk.main()
